<?php
class PostDataController extends Zend_Controller_Action
{
	public function init()
	{
		$this->_key_export	= '2506Txp';
		$mixKey	= $this->_request->getParam('ex', null);
		
		if($mixKey!=$this->_key_export){
			IndexController::initAdmin($this);
		}
		
		$this->_arrKey_Data	= array('sku', 'product_name', 'total_sales', 't_4', 't_3', 't_2', 't_1', 'exponential_smoothening', 'moving_average', 'tsl', 'asl', 'msl', 'in_transit', 'reorder');
		
		$this->_arrKeySale	= array('date', 'sku', 'product_name', 'category_level_1', 'price_on_website', 'price_paid_by_customer', 'item_level_status', 'order_level_status', 'supplier_lead_time', 'shipment_type');
	}
	
	#Upload Forecast Data
	public function indexAction()
	{		
		$objSale		= new QSale($this->AppUI->country);
		$intTotalSale	= $objSale->total();
		if($intTotalSale>0)
		{
			$objCategory	= new CCategory($this->AppUI->country);
			$arrData		= $objCategory->get();
			$arrCategory	= isset($arrData['category']) ? $arrData['category'] : null;
			$arrParamT		= isset($arrData['T']) ? $arrData['T'] : null;
			
			$this->view->arrCategory	= $arrCategory;
			$this->view->arrParamT		= $arrParamT;
			$this->view->intTotalCate	= $arrCategory ? count($arrCategory) : 0;
		}
		$this->view->intTotalSale	= $intTotalSale;
	}
	
	public function saveAction()
	{
		set_time_limit(9999);
		ini_set('memory_limit', '-1');	
	
		$objFile		= isset($_FILES['file']) ? $_FILES['file'] : null ;
		$strDelimiter	= $this->_request->getParam('strDelimiter');
	
		if(!$objFile['name'])
		{
			echo '<script>parent.show_error("forecastdata", "null")</script>';
			exit;
		}
		if($objFile)
		{
			#Drop Column
			$objColumn		= new QColumn($this->AppUI->country);
			$arrColumn		= $objColumn->get(0);
			if($arrColumn)
			{
				$obj		= new QBForecast($this->AppUI->country);
				foreach($arrColumn as $data){
					$obj->drop_column($data['icolumn'], 0);
				}
			}
			#Drop Column
			
			$arrKey			= $this->_arrKey_Data;
			$db				= Zend_Registry::get('db');
			$strQuery		= "
				TRUNCATE ".$this->AppUI->country."_forecasts;
				LOAD DATA LOCAL INFILE '".str_replace('\\', '/', $objFile['tmp_name'])."' 
					INTO TABLE ".$this->AppUI->country."_forecasts 
					FIELDS TERMINATED BY ',' ENCLOSED BY '\"'
					LINES TERMINATED BY '\r\n'
					IGNORE 1 LINES
					(".implode(',', $arrKey).")
				";
			
			$db		= Zend_Registry::get('db');
			$db->execute($strQuery);
			
			#Update Productname name category for forecats table
			$strQuery ="Update " . $this->AppUI->country . "_forecasts f Inner join " . $this->AppUI->country  . "_sales s ON s.sku = f.sku 
						 SET f.category = s.category_level_1, f.product_name =  s.product_name;";
			$db->execute($strQuery);
			
			#Bucket
			$objSale		= new QSale($this->AppUI->country);
			$arrTopItem		= $objSale->get_top_sku('items');
			$arrTopRevenue	= $objSale->get_top_sku('revenue');
			
			$strQuery	= '
					UPDATE '.$this->AppUI->country.'_forecasts SET _bucket="long_tail"  , bucket_id = 4 
					WHERE _bucket IS NULL OR _bucket="" ';
			$db->execute($strQuery);
			if($arrTopItem)
			{
				$strQuery	= '
					UPDATE '.$this->AppUI->country.'_forecasts SET _bucket="volume_driver" , bucket_id = 2 
					WHERE LOWER(sku) IN ("'.strtolower(implode('","', $arrTopItem)).'")';
				$db->execute($strQuery);
			}
			if($arrTopRevenue)
			{
				$strQuery	= '
					UPDATE '.$this->AppUI->country.'_forecasts SET _bucket="revenue_driver" , bucket_id = 3 
					WHERE LOWER(sku) IN ("'.strtolower(implode('","', $arrTopRevenue)).'")';
				$db->execute($strQuery);
			}
			if($arrTopItem && $arrTopRevenue)
			{
				$strQuery	= '
					UPDATE '.$this->AppUI->country.'_forecasts SET _bucket="cash_cow", bucket_id = 1  
					WHERE LOWER(sku) IN ("'.strtolower(implode('","', $arrTopItem)).'") AND LOWER(sku) IN ("'.implode('","', $arrTopRevenue).'"); ';
				$db->execute($strQuery);
			}
			#Bucket
			
			#WMS
			$obj		= new QBForecast($this->AppUI->country);
			$arrData	= $obj->get_all();
			CrontabController::update_WMS($arrData, $this->AppUI->country);
			#WMS
			
			CCommon::clear_chart_cache($this->AppUI->country);
			
			#Cancellation Rate
			$objSale->_cancellation_rate($arrData);
			#Cancellation Rate
			
			$db->closeConnection();
			
			echo '<script>parent.update_done();</script>';
		}
		exit;
	}
	
	#Upload Forecast Data
		
	public function resetDatabaseAction()
	{
		$strCallback	= $this->_request->getParam('callback');
		if($strCallback)
		{
			$obj	= new QBForecast($this->AppUI->country);
			$obj->reset();
			header('Location:'.HOST.'/post-data');
		}
		exit;
	}
	
	#Sale Data
	public function saveSaleAction()
	{
		ini_set('memory_limit', '-1');	
		$objFile	= isset($_FILES['file']) ? $_FILES['file'] : null ;
	
		if(!$objFile['name'])
		{
			echo '<script>parent.show_error("saledata", "null")</script>';
			exit;
		}
		if($objFile)
		{
			$strDelimiter	= $this->_request->getParam('strDelimiter');
			
			$arrKey			= $this->_arrKeySale;
			$db				= Zend_Registry::get('db');
			$strQuery		= "
				TRUNCATE ".$this->AppUI->country."_sales;
				LOAD DATA LOCAL INFILE '".str_replace('\\', '/', $objFile['tmp_name'])."' 
					INTO TABLE ".$this->AppUI->country."_sales 
					FIELDS TERMINATED BY ',' ENCLOSED BY '\"'
					LINES TERMINATED BY '\r\n'
					IGNORE 1 LINES
					(".implode(',', $arrKey).")
				";
			$db->execute($strQuery);
			
			$obj					= new QSale($this->AppUI->country);
			$arrData				= array();
			$arrData['category']	= $obj->get_category();
			$objCategory	= new CCategory($this->AppUI->country);
			$objCategory->save($arrData);
			
			$obj->_cal_top_sku();
			
			CCommon::clear_chart_cache($this->AppUI->country);
			$db->closeConnection();
			echo '<script>parent.update_done();</script>' . $objFile;
			exit;
		}
		exit;
	}
		
	public function resetSaleDatabaseAction()
	{
		$strCallback	= $this->_request->getParam('callback');
		if($strCallback)
		{
			//Clear data sales
			$obj	= new QSale($this->AppUI->country);
			$obj->reset();
			
			//Clear data Forecasts.			
			$objForeCastsd	= new QBForecast($this->AppUI->country);
			$objForeCastsd->reset();
			
			header('Location:'.HOST.'/post-data');
		}
		exit;
	}
	#Sale Data
	
	#Paramater
	public function saveParamaterAction()
	{
		if($this->_request->isPost())
		{
			$intTotalCate	= $this->_request->getParam('intTotalCate', 0);
			if($intTotalCate>0)
			{
				$arrCateData	= array();
				for($i=0; $i<$intTotalCate; $i++)
				{
					$strCategory		= $this->_request->getParam('strCategory'.$i, null);
					$strSaleDateFrom	= $this->_request->getParam('strSaleDateFrom'.$i, null);
					$strSaleDateTo		= $this->_request->getParam('strSaleDateTo'.$i, null);
					$intForecastDate	= $this->_request->getParam('intForecastDate'.$i, null);
					$intBufferDate		= $this->_request->getParam('intBufferDate'.$i, null);
					#$intSupplierTime	= $this->_request->getParam('intSupplierTime'.$i, null);
					
					$strSaleDateFrom1	= $this->_request->getParam('strSaleDateFrom1_'.$i, null);
					$strSaleDateTo1		= $this->_request->getParam('strSaleDateTo1_'.$i, null);
					$intForecastDate1	= $this->_request->getParam('intForecastDate1_'.$i, null);
					$intBufferDate1		= $this->_request->getParam('intBufferDate1_'.$i, null);
					
					$arrCateData[]		= array
					(
						'name'	=> $strCategory,
						's_df'	=> $strSaleDateFrom,
						's_dt'	=> $strSaleDateTo,
						'fd'	=> $intForecastDate,
						'bd'	=> $intBufferDate,
						's_df1'	=> $strSaleDateFrom1,
						's_dt1'	=> $strSaleDateTo1,
						'fd1'	=> $intForecastDate1,
						'bd1'	=> $intBufferDate1
					);
				}
				
				$arrData				= array();
				$arrData['category']	= $arrCateData;
				$arrData['T']			= array(
					'w1'	=> $this->_request->getParam('w1'),
					'w2'	=> $this->_request->getParam('w2'),
					'w3'	=> $this->_request->getParam('w3'),
					'w4'	=> $this->_request->getParam('w4')
				);
				
				$objCategory	= new CCategory($this->AppUI->country);
				$objCategory->save($arrData);
				CCommon::clear_chart_cache($this->AppUI->country);
			}
			echo '<script>parent.update_done();</script>';
		}
		exit;
	}
	#Paramater
	
	#Supplier Data
	public function saveSupplierAction()
	{
		set_time_limit(9999);
		ini_set('memory_limit', '-1');	
		$objFile	= isset($_FILES['file']) ? $_FILES['file'] : null ;
		if(!$objFile['name'])
		{
			echo '<script>parent.show_error("supplier", "null")</script>';
			exit;
		}
		if($objFile)
		{
			$strDelimiter	= $this->_request->getParam('strDelimiter');
			
			$arrKey			= array('sku', 'supplier');
			$db				= Zend_Registry::get('db');
			$strQuery		= "
				TRUNCATE ".$this->AppUI->country."_suppliers;
				LOAD DATA LOCAL INFILE '".str_replace('\\', '/', $objFile['tmp_name'])."' 
					INTO TABLE ".$this->AppUI->country."_sales 
					FIELDS TERMINATED BY ',' ENCLOSED BY '\"'
					LINES TERMINATED BY '\r\n'
					IGNORE 1 LINES
					(".implode(',', $arrKey).")
				";
			
			$db		= Zend_Registry::get('db');
			$db->execute($strQuery);
			$db->closeConnection();
			echo '<script>parent.update_done();</script>';
			exit;
		}
		exit;
	}
	#Supplier Data
}
?>
